﻿using System.Security.Principal;
using System.Web.Mvc;
using MvcContrib.Pagination;
using MvcContrib.Sorting;
using MvcContrib.UI.Grid;
using Webbness.Mvc.Models;
using Webbness.Mvc.SubSonic;

namespace Webbness.Mvc.Controllers
{
    public class ScaffoldController<T> : Controller where T : Record, new()
    {
        protected const int pageSize = 10;

        public virtual IPrincipal CurrentUser
        {
            get { return User; }
        }

        public virtual ActionResult Delete(int id)
        {
            var mod = Repository.Repo.Single<T>(id);
            return View("Scaffold", mod);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public virtual ActionResult Delete(int id, string confirmButton)
        {
            Repository.Repo.Delete<T>(id);
            ModelState.Clear();
            ViewData["results"] = "Deleted Successfully";
            return View("Scaffold");
        }

        public virtual ActionResult Edit(object id)
        {
            var mod = Repository.Repo.Single<T>(id);
            return View("Scaffold", mod);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public virtual ActionResult Edit(T mod)
        {
            if (ModelState.IsValid)
            {
                Repository.Repo.Update(mod);
                ModelState.Clear();
                RouteData.Values["action"] = "Display";
                ViewData["results"] = "Saved Successfully";
            }
            return View("Scaffold", mod);
        }

        public virtual ActionResult Display(object id)
        {
            var mod = Repository.Repo.Single<T>(id);
            return View("Scaffold", mod);
        }

        public virtual ActionResult Add()
        {
            var mod = new T();
            return View("Scaffold", mod);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public virtual ActionResult Add(T mod)
        {
            if (ModelState.IsValid)
            {
                object i = Repository.Repo.Add(mod);
                ViewData["results"] = "Saved Successfully";
                RouteData.Values["action"] = "Display";
                RouteData.Values["id"] = i.ToString();
                ModelState.Clear();
            }
            return View("Scaffold", mod);
        }

        public virtual ActionResult Error()
        {
            return View("Error");
        }

        public virtual ActionResult Index(int? page, GridSortOptions sort)
        {
            ViewData["sort"] = sort;
            var queryable = Repository.Repo.All<T>();

            queryable = string.IsNullOrEmpty(sort.Column) ? queryable.OrderBy("Id", SortDirection.Ascending) : queryable.OrderBy(sort.Column, sort.Direction);

            var pagination = queryable.AsPagination(page ?? 1, pageSize);

            return View("Scaffold", pagination);
        }
    }
}